package com.sinoglobal.dumping.activity;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentTabHost;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TextView;

import com.sinoglobal.dumping.DumplingInterface;
import com.sinoglobal.dumping.R;
import com.sinoglobal.dumping.base.Dumpling_DeviceUtils;
import com.sinoglobal.dumping.base.Dumpling_ShareAbstractActivity;
import com.sinoglobal.dumping.base.Dumpling_SharedPreferenceUtil;
import com.sinoglobal.dumping.base.Dumpling_SinoBaseActivity;
import com.sinoglobal.dumping.base.Dumpling_SinoBaseFragment;
import com.sinoglobal.dumping.base.Dumpling_SinoConfig;
import com.sinoglobal.dumping.base.Dumpling_SinoConstans;
import com.sinoglobal.dumping.bean.Dumpling_ShareInfoResultList;
import com.sinoglobal.dumping.fragment.Dumpling_HomeFragment;
import com.sinoglobal.dumping.fragment.Dumpling_MakeDumplingFragment;
import com.sinoglobal.dumping.fragment.Dumpling_MyDumplingFragment;
import com.sinoglobal.dumping.fragment.helper.Dumpling_HomefragmentImpl;
import com.sinoglobal.dumping.dumplingspring.DumplingObserver;
import com.sinoglobal.dumping.util.Dumpling_HttpMethodSet;
import com.sinoglobal.dumping.view.Dumpling_GetDumplingDialog;
import com.sinoglobal.dumpling.service.Dumpling_CopyFileService;
import com.sinoglobal.dumpling.service.Dumpling_DataRecycleServer;

import java.util.ArrayList;
import java.util.List;
@SuppressLint("HandlerLeak")
public class Dumpling_MainActivity extends Dumpling_ShareAbstractActivity implements DumplingObserver {

    private FragmentTabHost tabHost;
    private View contentView;
    public ImageView share, float_toupiao;
    private int tabString[] = {R.string.dumpling_daohang_1, R.string.dumpling_daohang_2, R.string.dumpling_daohang_3, R.string
            .dumpling_daohang_4};                      //tab标题
    private Class[] fragments = {                                                           //tab页的4个fragment
            Dumpling_HomeFragment.class,
            Dumpling_MakeDumplingFragment.class,
            Dumpling_MyDumplingFragment.class, Dumpling_SinoBaseFragment.class
    };
    public static final String USERNAME = "userName";                                       //用户名
    public static final String USERID = "userId";                                           //用户id
    public static final String ACTION = Dumpling_SinoConstans.DUMPLING_LOGIN_ACTION;        //广播频段
    private LogInReceiver mReceiver;                                                        //注册用广播接受者
    private ImageView float_tip;
    private String voteUrl;                                                                  //投票地址
    private static final int TAB_WIDGET_1 = 0;                                              //TAB页1
    private static final int TAB_WIDGET_2 = 1;                                              //TAB页2
    private static final int TAB_WIDGET_3 = 2;                                              //TAB页3
    private static final int TAB_WIDGET_4 = 3;                                              //TAB页4
    public static final String TEMP_ID_EVENT = "10001";                                     //分享活动模版
    public static final String TEMP_ID_MONEY = "10002";                                     //分享金额模版
    public static final String TEMP_ID_STRUT = "10003";                                     //炫耀一下模版
    public static final String TEMP_ID_MAKE = "10004";                                      //包饺子分享模版
    public static final String TEMP_ID_MAKE_EVENT = "10005";                                 //包饺子活动分享模版
    public static final String TEMP_ID_COUPON = "10006";                                     //包饺子优惠券分享模版
    public static final String TEMP_ID_CARD = "10007";                                     //包饺子贺卡分享模版
    private static final boolean DEBUG = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        contentView = View.inflate(Dumpling_MainActivity.this, R.layout.dumpling_activity_main, null);
        Dumpling_SinoConstans.IMEI = Dumpling_DeviceUtils.getIMEI(Dumpling_MainActivity.this);
        boolean flag = (Boolean) Dumpling_SharedPreferenceUtil.get(Dumpling_MainActivity.this, Dumpling_SinoConstans.DUMPLING_ALERT_WINDOW, false);
        setContentView(contentView);
        if (DEBUG) {
            mTemplateTitleText.setOnClickListener(this);
        }
        tabHost = getView(android.R.id.tabhost);
        share = getView(R.id.title_right_btn_share);
        float_toupiao = getView(R.id.float_toupiao);
        float_toupiao.setOnClickListener(this);
        share.setOnClickListener(this);
        initTab();
        initReceiver();
        startService(new Intent(Dumpling_MainActivity.this, Dumpling_DataRecycleServer.class));
        Intent copyIntent=new Intent(Dumpling_MainActivity.this,Dumpling_CopyFileService.class);
        copyIntent.putExtra("action","copyAPK");
        startService(copyIntent);
        initLogData();
        float_tip = getView(R.id.float_tip);
        float_tip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideViewForGone(float_tip);
            }
        });
        if (!flag) {
            float_tip.setBackgroundResource(R.color.dumpling_gray3);
            showView(float_tip);
            Dumpling_SharedPreferenceUtil.put(Dumpling_MainActivity.this, Dumpling_SinoConstans.DUMPLING_ALERT_WINDOW, true);
        }
        Dumpling_HttpMethodSet.getShareContent(Dumpling_MainActivity.this, TEMP_ID_EVENT, "", "", "", "");
        Dumpling_HttpMethodSet.getShareContent(Dumpling_MainActivity.this, TEMP_ID_MAKE, "", "", "", "");
        Dumpling_HttpMethodSet.getShareContent(Dumpling_MainActivity.this, TEMP_ID_MAKE_EVENT, "", "", "", "");
        Dumpling_HttpMethodSet.getShareContent(Dumpling_MainActivity.this, TEMP_ID_CARD, "", "", "", "");
    }

    private void initLogData() {
        Dumpling_SinoConstans.USER_NAME = Dumpling_SharedPreferenceUtil.getUserName(Dumpling_MainActivity.this);
        Dumpling_SinoConstans.USER_ID = Dumpling_SharedPreferenceUtil.getUserId(Dumpling_MainActivity.this);
    }

    public void setVoteUrl(String voteUrl) {
        this.voteUrl = voteUrl;
    }

    /**
     * 初始化广播
     */
    private void initReceiver() {
        mReceiver = new LogInReceiver();
        IntentFilter mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(ACTION);
        Dumpling_MainActivity.this.registerReceiver(mReceiver, mIntentFilter);
    }

    /**
     * 初始化Tab页
     */
    private void initTab() {
        tabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
        int count = fragments.length;

        for (int i = 0; i < count; i++) {
            LinearLayout layout = (LinearLayout) View.inflate(this, R.layout.dumpling_daohang_item, null);
            TextView text = (TextView) layout.findViewById(R.id.item_text);
            setTabWidgetStyle(false, i, text);
            if (i == 0) {
                text.setBackgroundResource(R.drawable.dumpling_nav_selected_lett);
                text.setTextColor(Color.RED);
            }
            text.setText(getResources().getString(tabString[i]));
            TabHost.TabSpec tabSpec = tabHost.newTabSpec(String.valueOf(i)).setIndicator(layout);
            tabHost.addTab(tabSpec, fragments[i], null);
        }
        tabHost.getTabWidget().getChildTabViewAt(0).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tabHost.setCurrentTab(0);
                setTabWidgetStyle(true, TAB_WIDGET_1, ((LinearLayout) v).getChildAt(0));
            }
        });
        tabHost.getTabWidget().getChildTabViewAt(1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setTabWidgetStyle(true, TAB_WIDGET_2, ((LinearLayout) v).getChildAt(0));
                if (isNoLogIn(Dumpling_MainActivity.this)) {
                    setTabWidgetStyle(true, tabHost.getCurrentTab(), ((LinearLayout) tabHost.getTabWidget().getChildTabViewAt(tabHost.getCurrentTab())).getChildAt(0));
                    Intent intent = new Intent();
                    intent.setClass(Dumpling_MainActivity.this, Dumpling_NoPasswordQuicklyLoginActivity.class);
                    intent.putExtra("index", 1);
                    Dumpling_MainActivity.this.startActivity(intent);
                } else {
                    tabHost.setCurrentTab(1);
                }
                hideViewForGone(float_toupiao);
            }
        });
        tabHost.getTabWidget().getChildTabViewAt(2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                setTabWidgetStyle(true, TAB_WIDGET_3, ((LinearLayout) v).getChildAt(0));
                if (isNoLogIn(Dumpling_MainActivity.this)) {
//                    setTabWidgetStyle(true, tabHost.getCurrentTab(), ((LinearLayout) tabHost.getTabWidget().getChildTabViewAt(tabHost.getCurrentTab())).getChildAt(0));
                    Intent intent = new Intent();
                    intent.setClass(Dumpling_MainActivity.this, Dumpling_NoPasswordQuicklyLoginActivity.class);
                    intent.putExtra("index", 2);
                    Dumpling_MainActivity.this.startActivity(intent);
                } else {
//                  tabHost.setCurrentTab(2);
                    goMyDumpling();
                }
                hideViewForGone(float_toupiao);
            }
        });
        tabHost.getTabWidget().getChildTabViewAt(3).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isNoLogIn(Dumpling_MainActivity.this)) {
                    Intent intent = new Intent();
                    intent.setClass(Dumpling_MainActivity.this, Dumpling_NoPasswordQuicklyLoginActivity.class);
                    intent.putExtra("index", 1107);
                    Dumpling_MainActivity.this.startActivity(intent);
                } else {
                    goWallet();
                }
                hideViewForGone(float_toupiao);
            }
        });
    }

    /**
     * 设置Tab页样式
     */
    private void setTabWidgetStyle(boolean isClick, int index, View view) {
        if (isClick) {
            int count = tabHost.getTabWidget().getChildCount();
            for (int i = 0; i < count; i++) {
                View itemView = ((LinearLayout) tabHost.getTabWidget().getChildAt(i)).getChildAt(0);
                setTabWidgetStyle(false, i, itemView);
            }
            View itemView = ((LinearLayout) tabHost.getTabWidget().getChildAt(index)).getChildAt(0);
            if (index == 0) {
                itemView.setBackgroundResource(R.drawable.dumpling_nav_selected_lett);
            } else if (index == 3) {
                itemView.setBackgroundResource(R.drawable.dumpling_nav_selected_right);
            } else {
                itemView.setBackgroundColor(Color.WHITE);
            }
            ((TextView) view).setTextColor(Color.RED);
            return;
        }
        switch (index) {
            case TAB_WIDGET_1:
                view.setBackgroundResource(R.drawable.dumpling_nav_normal_left);
                ((TextView) view).setTextColor(Color.WHITE);
                break;
            case TAB_WIDGET_2:
                view.setBackgroundResource(R.drawable.dumpling_nav_normal_middle);
                ((TextView) view).setTextColor(Color.WHITE);
                break;
            case TAB_WIDGET_3:
                view.setBackgroundResource(R.drawable.dumpling_nav_normal_middle);
                ((TextView) view).setTextColor(Color.WHITE);
                break;
            case TAB_WIDGET_4:
                view.setBackgroundResource(R.drawable.dumpling_nav_normal_right);
                ((TextView) view).setTextColor(Color.WHITE);
                break;
        }

    }

    /**
     * 跳转到包饺子页面
     */
    public void setTabHost() {
        tabHost.setCurrentTab(1);
        setTabWidgetStyle(true, TAB_WIDGET_2, ((LinearLayout) tabHost.getTabWidget().getChildTabViewAt(1)).getChildAt(0));
    }

    @Override
    protected void onResume() {
        Dumpling_HomefragmentImpl.mContext = this;
        initLogData();

        super.onResume();
    }

    @Override
    public void onAntiViolence(View view) {
        if (view.getId() == R.id.dumpling_title_right_btn_treaty) {
            Intent mIntent = new Intent();
            mIntent.setClass(Dumpling_MainActivity.this, Dumpling_ActionRulesActivity.class);
            startActivity(mIntent);
        } else if (view.getId() == R.id.title_right_btn_share) {
            Dumpling_ShareInfoResultList resultList = null;
            String tempId = "";
            if (tabHost.getCurrentTab() == 0) {        //捞饺子活动
                resultList = Dumpling_SinoConfig.sEventShare.getResultList();
                tempId = TEMP_ID_EVENT;
            } else if (tabHost.getCurrentTab() == 1) {  //包饺子活动
                resultList = Dumpling_SinoConfig.sMakeEventShare.getResultList();
                tempId = TEMP_ID_MAKE_EVENT;
            }
            if (resultList != null) {
                if (!Dumpling_SinoBaseActivity.isNoLogIn(Dumpling_MainActivity.this)) {
                    Dumpling_HttpMethodSet.markShare(this, Dumpling_SinoConstans.USER_ID);
                }
                setShare(resultList.getContent(),
                        resultList.getTitle(),
                        null,
                        resultList.getUrl() + "?productCode=" + Dumpling_SinoConstans.PRODUCT_CODE,
                        0,
                        resultList.getPicurl());
            } else {
                Dumpling_HttpMethodSet.getShareContent(Dumpling_MainActivity.this, tempId, "", "", "", "");
                showToast("网络情况较差，请稍后重试");
            }
        } else if (view.getId() == R.id.float_toupiao) {
            if (Dumpling_SinoBaseActivity.isNoLogIn(this)) {
                goIntent(Dumpling_NoPasswordQuicklyLoginActivity.class);
                return;
            }
            Intent intent = new Intent(Dumpling_MainActivity.this, Dumpling_VoteActivity.class);
            intent.putExtra("url", voteUrl + "?userid=" + Dumpling_SinoConstans.USER_ID + "&productCode=" + Dumpling_SinoConstans.PRODUCT_CODE);
            startActivity(intent);
        } else if (view == mTemplateTitleText) {
            DumplingInterface.logout(Dumpling_MainActivity.this);
        }
    }

    @Override
    public void update(Dumpling_HomeFragment fragment, boolean isChangeUI, boolean isVote) {
        if (isVote && tabHost.getCurrentTab() == 0) {
            showView(float_toupiao);
        } else {
            hideViewForGone(float_toupiao);
        }
    }


    /**
     * 用户登录广播
     */
    public class LogInReceiver extends BroadcastReceiver {
        String action;

        public LogInReceiver() {
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            action = intent.getAction();
            if (action.equals(ACTION)) {
                String code = intent.getStringExtra("code");
                if (!TextUtils.isEmpty(code)) {

                    final int index = intent.getIntExtra("index", -2);
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            Message message = mHandler.obtainMessage();
                            message.what = index;
                            mHandler.sendMessage(message);
                        }
                    });
                    notifyLogInSuccess();// 观察者模式刷新

                }
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // super.onSaveInstanceState(outState);
    }

    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int index = msg.what;
            if (index >= 0) {
                if (index == 1107) {
                    goWallet();
                }
                if (index == 2) {
//                    tabHost.setCurrentTab(2);
//                    setTabWidgetStyle(true, TAB_WIDGET_3, ((LinearLayout) tabHost.getTabWidget().getChildTabViewAt(2)).getChildAt(0));
                    goMyDumpling();
                }
                if (index == 1) {
                    tabHost.setCurrentTab(1);
                    setTabWidgetStyle(true, TAB_WIDGET_2, ((LinearLayout) tabHost.getTabWidget().getChildTabViewAt(1)).getChildAt(0));
                }
            }
        }
    };

    /**
     * 跳转到钱包页面
     */
    public void goWallet() {
        try {
            Intent intent = new Intent();
            intent.setClass(this, com.sinoglobal.wallet.activity.W_HomeActivity.class);
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 跳转到 我的饺子
     */
    protected void goMyDumpling() {
        Intent intent = new Intent(this, Dumpling_MyDumplingActivity.class);
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mHandler!=null){
            mHandler.removeCallbacksAndMessages(null);
        }
        unregisterReceiver(mReceiver);
        Dumpling_SinoConstans.USER_ID = "";
        Dumpling_SinoConstans.USER_NAME = "";
    }

}
